﻿using Newtonsoft.Json.Linq;
using Qianke.Core.Common.Interface;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace Qianke.Core.Common
{
    public class HttpHelper : ITransientDependency
    {
        public IAbpLazyServiceProvider LazyServiceProvider { get; set; }

        public async Task<TResult> Post<TResult>(string url, string paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            using (var client = new HttpClient())
            {
                using (var context = new StringContent(paramBody, Encoding.UTF8))
                {
                    context.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    optionHeader?.Invoke(context.Headers);
                    var result = await client.PostAsync(url, context);
                    if (!result.IsSuccessStatusCode)
                        throw new Exception(result.ToString());
                    var strHtml = await result.Content.ReadAsStringAsync();
                    return strHtml.ToObject<TResult>();
                }
            }
        }

        public async Task<TResult> Get<TResult>(string url, HttpCompletionOption options = HttpCompletionOption.ResponseContentRead)
        {
            using (var client = new HttpClient())
            {
                var result = await client.GetAsync(url,options);
                if (!result.IsSuccessStatusCode)
                    throw new Exception(result.ToString());
                var strHtml = await result.Content.ReadAsStringAsync();
                return strHtml.ToObject<TResult>();
            }
        }


        public  async Task<ReturnInfo> CallApi<TResultData>( string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            return await Post<ReturnInfoData<TResultData>>(url, paramBody.ToJson(), optionHeader);
        }

        public  Task<ReturnInfo> TokenCallApi<TResultData>( string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            JToken jToken = paramBody?.ToJson().ToObject<JToken>() ?? new JObject();
            if (string.IsNullOrEmpty(jToken["Token"].SafeToString()))
            {
                var tokenInfo = LazyServiceProvider.LazyGetService<ITokenInfo>();
                jToken["Token"] = TokenHelper.CreateToken(tokenInfo);
            }
            return CallApi<TResultData>(url, jToken, optionHeader);
        }

        public  Task<ReturnInfo> CallChildApi<TResultData>( string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            JToken jToken = paramBody?.ToJson().ToObject<JToken>() ?? new JObject();
            if (jToken["OrganId"].ToInt64(0L) == 0)
            {
                var tokenInfo = LazyServiceProvider.LazyGetService<ITokenInfo>();
                if (tokenInfo.Id > 0)
                {
                    jToken["Token"] = TokenHelper.CreateToken(tokenInfo);
                    jToken["OrganId"] = tokenInfo.OrganId;
                    jToken["ManagerId"] = tokenInfo.Id;
                }
            }
            return CallApi<TResultData>(url, jToken, optionHeader);
        }

    }
}
